#include "client.h"
#include <stdio.h>   // printf, fprintf
#include <stdlib.h>  // atoi, exit

int main(int argc,char * argv[])
{
    const char * ip = argv[1];
    char * endptr;
    unsigned short port = strtoul(argv[2], &endptr, 10);
    int clientfd = tcpConnect(ip, port);

    char buf[128] = {0};

    //4. 使用select进行监听
    fd_set rdset;
    train_t t;
    while(1) {
        FD_ZERO(&rdset);
        FD_SET(STDIN_FILENO, &rdset);
        FD_SET(clientfd, &rdset);
        
        int nready = select(clientfd + 1, &rdset, NULL, NULL, NULL);
        printf("nready:%d\n", nready);
        if(FD_ISSET(STDIN_FILENO, &rdset)) {
            //读取标准输入中的数据
            memset(buf, 0, sizeof(buf));
            int ret = read(STDIN_FILENO, buf, sizeof(buf));
            if(0 == ret) {
                printf("byebye.\n");
                break;
            }
            memset(&t, 0, sizeof(t));
            //解析命令行
            buf[strlen(buf)-1] = '\0';
            parseCommand(buf, strlen(buf) - 1, &t);
            sendn(clientfd, &t, 4 + 4 + t.len);
        } else if(FD_ISSET(clientfd, &rdset)) {
            if(!strcmp(buf, "gets")) {
                getsFile(clientfd);
            }
        }
    }
    close(clientfd);
    return 0;
}
